import React from 'react'
import { Table,Icon,Modal,Popconfirm,Message,Form,Row,Select,Col,Button,Input,DatePicker} from 'antd';
const FormItem = Form.Item;
import api from '../../../api/dictionarie';

import PanelBox from '../../../components/PanelBox';
import DictForm from '../../Form/Dict';
const { RangePicker } = DatePicker;

export default class TablePage extends React.Component {
  columns = [{
    title: '字典TYPE',
    key: 'type',
    dataIndex: 'type',
    sorter: true,
    width: '20%',
  }, {
    title: '字典VALUE',
    key: 'value',
    dataIndex: 'value',
    width: '20%',
  }, {
    title: '字典LABEL',
    key: 'label',
    dataIndex: 'label',
  }, {
    title: '排序',
    key: 'sort',
    dataIndex: 'sort',
  }/*, {
    title: '状态',
    dataIndex: 'del_flag',
    render:(text, record, index) =>  {
        switch(record.userType){
          case '1':
            return '有效';
          case '0':
            return '无效';
          default:
            return '未知';
        }
      },
  }*/, {
    title: '操作',
    key: 'id',
    dataIndex: 'id',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={() =>this.startCreateUser(record.type)} >添加</a>
        <span className="ant-divider" />
        <a href="javascript:void(0)"  onClick={() =>this.startUpdateUser(record)} >编辑</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除跟用户?" onConfirm={() => this.handleLogOut(text)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];

  state = { 
    data: [],
    listtype: [],
    child:[],
    pagination: {},
    loading: false,
    isOpenCreateUser: false,
    isOpenEditUser: false,
  };
  handleTableChange = (pagination, filters, sorter) => {
    const pager = this.state.pagination;
    pager.current = pagination.current!=null?pagination.current:pagination.pageNum;
    this.setState({
      pagination: pager,
    });
    this.fetch({
      pageSize: pagination.pageSize,  //每页现实条数
      pageNum: pagination.current,  //当前页数
      sortField: sorter.field,
      sortOrder: sorter.order,
      type:this.default!='' ? this.default : '',
      ...filters, 
    });
  }

   rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      //console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      this.setState({
        delIds: `${selectedRowKeys}`,
      });
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
    }),
  };

  default='';
  fetch = (params = {}) => {
    this.setState({ loading: true });
    if(params.type!=''){
      this.default=params.type;
    }
    api.get('/fillallDict', {   //分业查询所有
      ...params,
      responseType: 'json'
    }).then((data) => {
      data = data.data;
      const pagination = data;
      pagination.total = data.pages*data.pageSize;
      this.setState({
        loading: false,
        data: data.list,
        pagination,
      });
    });
  } 
  
   handleSelect= (params = {}) => {
    let childrend=[];
    childrend =this.state.child;
    const Option = Select.Option;
    api.get('/queryDict', {   //查询所有
    }).then((data) => {
      data.data.forEach(function(value, index, array) {
        childrend.push(<Option key={value.type} >{value.type}</Option>);
       }) 
       this.state.child=childrend; 
    });
}


   componentDidMount = () =>{
    this.fetch({
      pageSize: 20,
      pageNum: 1
    });
     this.handleSelect();
  }

  sort = 10;
  type = '';
  startCreateUser = (type) =>{
    if(this.resetFields)this.resetFields();
    this.handType(type);
  }
  startCreateUser_default = () =>{
    if(this.resetFields)this.resetFields();
    this.sort = 10;
    this.type = '';
    this.setState({
      isOpenCreateUser: true,
    });
  }
  
  closeCreateUser = () =>{
    this.setState({
      isOpenCreateUser: false,
    });
  }
  closeaddDict = () =>{
    this.setState({
      isOpenCreateUser: false,
    });
    this.handleTableChange(this.state.pagination,{},{});
  }
  startUpdateUser = (record) =>{
    if(this.resetFields)this.resetFields();
      this.setState({
        isOpenEditUser: true,
        rowRecord:record,
      });
  }
  closeUpdateUser = () =>{
    this.setState({
      isOpenEditUser: false,
    });
  }
  closeupdateDict = () =>{
    this.setState({
      isOpenEditUser: false,
    });
    this.handleTableChange(this.state.pagination,{},{});
  }

  deleteAll = () => {
    const ids = this.state.delIds;
    if(ids == '' || ids == null){
      Message.error('请选择你要删除的字典！');
      return;
    }
    this.handleLogOut(ids);
   }

   
  handleLogOut = (id) => {
    const {logout} = this.props
    api.delete('/deleteDict', {id:id}).then((data) => {
      const result=data.data;
      if(result.code==0){
        Message.success('删除成功！');
        this.handleTableChange(this.state.pagination,{},{});
      }else{
        Message.error("删除失败");
      }
    });
   /* logout().payload.promise.then(() => {

      this.props.history.replace('/login');
    });*/
  }

  handType = (type) => {
     api.get('/maxSort', 
     {
       type:type
     }).then((data) => {
      if(data!=''){
          this.sort=data.data;
          this.type=type;
          this.setState({
            isOpenCreateUser: true,
          });
      }
    }); 
  }
  // 接收子组件传入的数据及其方法
  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }


  render() {
    let _this = this;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    class CustomizedForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {   //提交后得到from表单中得值
          if (!err) {
             _this.fetch({type:values.type, pageSize: 20,pageNum: 1});
             _this.default=values.type;
          }
        });
        return false;
      }

      render() {
        const { getFieldDecorator} = this.props.form;
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem {...formItemLayout} label="字典类型" style={{marginRight:'10px'}}>
            {getFieldDecorator('type', {
                  initialValue:_this.default ? _this.default: ''
              })(
                <Select
                  mode="combobox"
                  style={{ width: 200 }}
                  placeholder="选择一个字典类型"
                >
                  {_this.state.child}
                </Select>
            )}
          </FormItem>
          <FormItem style={{marginRight:'10px'}}>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem>
          <FormItem style={{marginRight:'10px'}}>
            <Button type="primary" icon="plus" onClick={_this.startCreateUser_default}>新建字典</Button>
          </FormItem>
        </Form>
      }
    }
    const CusForm = Form.create({})(CustomizedForm);

    return (
      <div>
        <CusForm/>
        <PanelBox>
          <Table columns={this.columns}
            rowKey={record => record.id}
            dataSource={this.state.data}
            pagination={this.state.pagination}
            loading={this.state.loading}
            onChange={this.handleTableChange}
           /*  rowSelection={this.rowSelection} */
          />
        </PanelBox>
        <Modal
          title="新增字典"
          visible={this.state.isOpenCreateUser}
          onOk={this.closeCreateUser}
          onCancel={this.closeCreateUser}
          wrapClassName="vertical-center-modal"
          width="1000"
          footer={null}
        >
          <DictForm addfinish={this.closeaddDict} close={this.closeCreateUser} Dictsort={this.sort} Dicttype={this.type} callbackParent={this.initChildrenParams}/>
        </Modal>
        <Modal
          title="编辑字典"
          visible={this.state.isOpenEditUser}
          onOk={this.closeUpdateUser}
          onCancel={this.closeUpdateUser}
          wrapClassName="vertical-center-modal"
          
          width="1000"
          footer={null}
        >
          <DictForm upfinish={this.closeupdateDict} close={this.closeUpdateUser} rowRecord={this.state.rowRecord} callbackParent={this.initChildrenParams}/>
        </Modal>
      </div>
    );
  }
}
